<?php

namespace App\Services;

use App\Models\CompanyUser;
use App\Models\Department;
use App\Models\DepartmentUser;
use App\Models\User;

class DepartmentService extends BaseService
{
    /**
     * 获取数据列表
     */
    public function getList($perPage)
    {
        $list = Department::query()->paginate($perPage);

        return $list->isNotEmpty() ? $list->toArray() : [];
    }

    /**
     * 获取部门员工
     */
    public function getUsers($departmentId)
    {
        $userIds = DepartmentUser::query()->where('department_id', $departmentId)->pluck('user_id');

        $users = User::query()->whereIn('id', $userIds)->select(['id', 'nickname'])->get();

        return $users->isNotEmpty() ? $users->toArray() : [];
    }

    /**
     * 用户是否是公司管理员
     */
    public function isCompanyAdminer($userId, $companyId)
    {
        return CompanyUser::query()
            ->where('user_id', $userId)
            ->where('company_id', $companyId)
            ->value('is_admin');
    }

    /**
     * 获取一条数据信息
     */
    public function getInfo($id)
    {

        return Department::query()->where('id', $id)->first()->toArray();
    }

    /**
     * 新增数据
     */
    public function addNewData($params)
    {
        $department = new Department();
        if(!$departmentId = $this->saveData($department, $params, 'insert')){
            return false;
        }
        return $departmentId;
    }

    /**
     * 修改数据
     */
    public function updateData($id, $params)
    {
        $department = Department::query()->find($id);
        if(!$this->saveData($department, $params, 'update')){
            return false;
        }
        return $id;
    }

    /**
     * 保存数据
     */
    public function saveData($department, $params)
    {
        if (empty($params['id'])) { //修改的话，不涉及修改这里
            $parentType = $this->getParentType($params); //上级类型
            $department->company_id = $params['company_id'] ?? 0; //上级是否为公司
            $department->department_id = $params['department_id'] ?? 0; //上级是否为部门
            $department->part_company_id = $params['part_company_id'] ?? 0; //上级是否参建单位id
            $department->project_id = $params['project_id'] ?? 0; //上级是否项目
            $department->parent_type = $parentType;
        }
        $department->title = $params['title']; //部门名称
        if (!$department->save()) {
            return false;
        }
        return $department->id;
    }

    /**
     * 获取父级类型
     */
    private function getParentType($args)
    {
        if (!empty($args['department_id'])) {
            return Department::PARENT_DEPT;//新建部门的上级是部门的情况
        } elseif (!empty($args['project_id'])) {
            return Department::PARENT_PROJECT;//新建部门的上级是项目的情况
        } elseif (!empty($args['part_company_id'])) {
            return Department::PARENT_PART_COMPANY;//新建部门的上级是参建单位的情况
        } elseif (!empty($args['company_id'])) {
            return Department::PARENT_COMPANY;//新建部门的上级是公司的情况
        }
        return 0;
    }

    /**
     * 获取子树
     */
    function getTree($array, $id = 0)
    {
        $tree = array();
        foreach ($array as $key => $value) {
            if (in_array($id, explode(',', $value['department_id']))) {
                $value['children'] = $this->getTree($array, $value['id']);
                if (!$value['children']) {
                    unset($value['children']);
                }
                $tree[] = $value;
            }
        }
        return $tree;
    }

    /**
     * 返回部门以及子部门下的全部用户
     */
    public function userIds(int $departmentId)
    {
        $departmentIds = $this->getChildDepartmentIds([$departmentId]);
        $userIds = DepartmentUser::query()
            ->distinct()
            ->whereIn('department_id', $departmentIds)
            ->pluck('user_id');

        return $userIds->isNotEmpty() ? $userIds->toArray() : [];
    }

    /**
     * 返回当前部门和子部门的所有部门id
     */
    private function getChildDepartmentIds($departmentIds = [])
    {
        $childDepartmentIds = Department::query()->whereIn('department_id', $departmentIds)->pluck('id'); //当前部门的子部门
        if ($childDepartmentIds->isNotEmpty()) {
            $childDepartmentIds = $childDepartmentIds->toArray();
            $resultIds = array_merge($departmentIds, $childDepartmentIds); //合并
            return array_unique($resultIds); //去重
        }

        return $departmentIds;
    }
}
